package com.dson.monitor;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.Map;

@Activate(group = {CommonConstants.PROVIDER,CommonConstants.CONSUMER})
public class MonitorFilter implements Filter {

    private final Monitor monitor =  new Monitor();

    public MonitorFilter() {
        new Thread(monitor).start();
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        long start = System.currentTimeMillis();
        Result invoke = invoker.invoke(invocation);
        long end = System.currentTimeMillis();
        long costTime = end - start;
        String method = invocation.getMethodName();
        Map<Long, Long> methodMap = monitor.costTimeMaps.get(method);
        if(methodMap == null){
            methodMap = new HashMap<>();
        }
        methodMap.put(end,costTime);
        monitor.costTimeMaps.put(method,methodMap);

        return invoke;
    }
}
